package com.isotronica.neveras.logica;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class VirtualConsoleManager extends Thread{
	
	private Socket socket;
	private Controlador miControlador;
	private InputStream inputStream;
	private OutputStream outputStream;
	private Thread t;
	private int conTimeOut;
	private PrintWriter out;
	private BufferedReader in;
	
	
	public VirtualConsoleManager(Socket socket, Controlador miControlador) {
		
		this.socket = socket;
		this.miControlador = miControlador;
		
		try {
			inputStream = this.socket.getInputStream();
			outputStream = this.socket.getOutputStream();
			in = new BufferedReader(new InputStreamReader(
					inputStream));
			out = new PrintWriter(outputStream, 
	                 true);


		} catch (IOException e) {
			e.printStackTrace();
		}
		t = new Thread(this);
		t.setPriority(NORM_PRIORITY);
		t.start();
		System.out.println("Sesion virtual Iniciada");
	}

	

	public void run() {
		
		
	
		while (conTimeOut < 6) {
			try {
				sleep(9000);
			} catch (InterruptedException e) {
			}
			conTimeOut++;
			try {
				if(socket.isConnected() && !socket.isClosed()){
					
					
					out.println(miControlador.getVirtualConsole());
					while(in.ready()){
						conTimeOut =0;
						in.readLine();						
					}
					
				}else{
					socket.close();
					System.out.println("Sesion virtual Finalizada");
				}
					
				//while (inputStream.available() > 0) {
					
				//}
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				try {
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		}
		System.out.println("Sesion virtual Finalizada");
	}
		

}
